# Create your views here.
import json

from django.shortcuts import get_list_or_404
from django.shortcuts import render
from rest_framework import generics
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from .models import Stack, Fund, ConvBond
from .serializers import StackSerializer, FundSerializer, ConvBondSerializer

# 缓存数据
# 远程提交SAVE_XXX 来修改此处值
# 前端实时读取此处值， XXX_VIEW
STACK_DATA = []
CONVBOND_DATA = []
FUND_DATA = []


class SaveStack(APIView):
    def post(self, request, *args, **kwargs):
        data = request.POST.get('data')
        global STACK_DATA
        STACK_DATA = json.loads(data)
        return Response({'status': '上传成功'})

    def get(self, request, *args, **kwargs):
        return Response({'status': '链接成功'})


class SaveConvBond(APIView):
    def post(self, request, *args, **kwargs):
        data = request.POST.get('data')
        global CONVBOND_DATA
        CONVBOND_DATA = json.loads(data)
        return Response({'status': '上传成功'})

    def get(self, request, *args, **kwargs):
        return Response({'status': '链接成功'})


class SaveFund(APIView):
    def post(self, request, *args, **kwargs):
        data = request.POST.get('data')
        global FUND_DATA
        FUND_DATA = json.loads(data)
        return Response({'status': '上传成功'})

    def get(self, request, *args, **kwargs):
        return Response({'status': '链接成功'})


class Health(APIView):
    def get(self, request, *args, **kwargs):
        return Response({'status': '链接成功'})


class StackView(APIView):

    def get(self, request, *args, **kwargs):
        return_dic = {
            'code': 0,
            'msg': "OK",
            'count': 0,
            'data': []  # layUI table中会渲染JsonResponse中的data字段中字典的key作为field
        }
        global STACK_DATA
        return_dic['data'] = STACK_DATA
        return_dic['count'] = len(STACK_DATA)
        return Response(return_dic)


class ConvBondView(APIView):

    def get(self, request, *args, **kwargs):
        return_dic = {
            'code': 0,
            'msg': "OK",
            'count': 0,
            'data': []
        }
        global CONVBOND_DATA
        return_dic['data'] = CONVBOND_DATA
        return Response(return_dic)


class FundView(APIView):

    def get(self, request, *args, **kwargs):
        return_dic = {
            'code': 0,
            'msg': "OK",
            'count': 0,
            'data': []
        }
        global FUND_DATA
        return_dic['data'] = FUND_DATA
        return_dic['count'] = len(FUND_DATA)
        return Response(return_dic)


class StubStack(APIView):
    """
    桩代码数据

    """

    def get(self, request, *args, **kwargs):
        return_dic = {
            'code': 0,
            'msg': "OK",
            'count': 0,
            'data': []  # layUI table中会渲染JsonResponse中的data字段中字典的key作为field
        }
        data = [
            {'code': '01919', 'name': '中远海控', 'time': '2021-02-23 16:00', 'hbuy1': '9.100', 'hsell1': '9.120',
             'abuy1': '9.100', 'asell1': '9.120'},
            {'code': '01033', 'name': '中石化油服', 'time': '2021-02-23 16:00', 'buy1': '0.820', 'sell1': '0.840'},
            {'code': '02866', 'name': '中远海发', 'time': '2021-02-23 16:00', 'buy1': '1.290', 'sell1': '1.300'},
            {'code': '01088', 'name': '中国神华', 'time': '2021-02-23 16:00', 'buy1': '15.100', 'sell1': '15.160'},
            {'code': '00857', 'name': '中国石油股份', 'time': '2021-02-23 16:00', 'buy1': '2.890', 'sell1': '2.920'}
        ]
        return_dic['data'] = data
        return Response(return_dic)


def HTMLHongKongStack(request):
    """
    :param request:
    :return:
    """
    t_path = 'stack.html'

    return render(request, t_path)


def HTMLLOFFund(request):
    """
    基金页面
    :param request:
    :return:
    """
    t_path = 'fund.html'
    return render(request, t_path)


def HTMLConvFond(request):
    """
    基金页面
    :param request:
    :return:
    """
    t_path = 'convbond.html'
    return render(request, t_path)


def HTMLTest(request):
    """
    测试

    :param request:
    :return:
    """
    t_path = 'test.html'
    return render(request, t_path)


class StackViewSet(ModelViewSet):
    queryset = Stack.objects.all()
    serializer_class = StackSerializer

    def retrieve(self, request, *args, **kwargs):
        user = self.get_object()

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop("partial", False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)


class ConvBondViewSet(ModelViewSet):
    queryset = ConvBond.objects.all()
    serializer_class = ConvBondSerializer

    def retrieve(self, request, *args, **kwargs):
        user = self.get_object()


class FundViewSet(ModelViewSet):
    queryset = Fund.objects.all()
    serializer_class = FundSerializer
    permission_classes = [AllowAny, ]

    def retrieve(self, request, *args, **kwargs):
        object = self.get_object()
        serializer = self.get_serializer(object)
        return Response(serializer.data)

    def update(self, request, *args, **kwargs):
        """
        patch请求调用的是partial_update操作

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        partial = kwargs.pop("partial", False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(serializer.data)


class GetRefreshStack(generics.ListAPIView):
    serializer_class = StackSerializer

    def get_queryset(self):
        stacks = get_list_or_404(Stack, s_flag_refresh=1)
        return stacks


class GetRefreshFund(generics.ListAPIView):
    serializer_class = FundSerializer

    def get_queryset(self):
        funds = get_list_or_404(Fund, f_flag_refresh=1)
        return funds
